
package com.weiqiao.mall.repository.impl;

import com.google.gson.Gson;
import com.mongodb.Block;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Filters;
import com.weiqiao.base.dao.impl.BaseMongoDaoImpl;
import com.weiqiao.mall.domain.MemberShipEntity;
import com.weiqiao.mall.repository.IMemberShipRepository;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * 会员中心配置 持久化层 实现层 继承IVipDao
 *
 * @author wangjian
 */
@Repository("MemberShipRepositoryImpl")
public class MemberShipRepositoryImpl extends BaseMongoDaoImpl implements IMemberShipRepository {
    private String collectionName = "membership_";

    private String collectionNameExport = "memberExportLog_";

    private String collectionNameone = "member_item";

    @Override
    public boolean addMember(int company_id, String json) {
        return this.inSert(collectionName + company_id, json);

    }

    @Override
    public boolean updateMember(int company_id, MemberShipEntity entity, int member_id) {
        Bson filter = Filters.eq("member_id", member_id);
        String json = new Gson().toJson(entity);
        Document doc = Document.parse(json);
        return this.updateOne(collectionName + company_id, filter, doc, false);
    }

    @Override
    public int findMaxMemberId(int company_id) {
        Document query = new Document();
        query.append("company_id", company_id);
        Document sort = new Document();
        sort.append("member_id", -1);
        List<String> findFilterSortSkipLimit = this.findFilterSortSkipLimit(collectionName + company_id, query, sort, 0, 1);
        if (CollectionUtils.isNotEmpty(findFilterSortSkipLimit)) {
            MemberShipEntity memberShipEntity = new Gson().fromJson(findFilterSortSkipLimit.get(0), MemberShipEntity.class);
            if (memberShipEntity != null) {
                return memberShipEntity.getMember_id();
            }
        }
        return 9999;
    }

    @Override
    public String queryMemberOneByFilter(int company_id, Bson filter) {
        String findOne = this.findOne(collectionName + company_id, filter);
        return findOne;
    }

    @Override
    public List<String> queryMemberListByFilter(int company_id, Bson filter) {
        List<String> list = this.findFilter(collectionName + company_id, filter);
        return list;
    }

    @Override
    public boolean updateBalance(int company_id, String phone, MemberShipEntity memberEntity, Double account) {
        Bson filter = Filters.eq("phone", phone);
        Bson filter2 = Filters.eq("company_id", company_id);
        Bson and = Filters.and(filter, filter2);
        memberEntity.setBalance(account);
        String json = new Gson().toJson(memberEntity);
        Document doc = Document.parse(json);
        return this.updateOne(collectionName + company_id, and, doc, false);
    }

    @Override
    public MemberShipEntity getTotalMemberRewardPoints(int companyid, Document doc) {

        Document match = new Document("$match", doc);
        Document group = new Document("$group", new Document("_id", "$company_id")
                .append("total_score", new Document("$sum", "$total_score"))
                .append("usable_score", new Document("$sum", "$usable_score"))
                .append("totaluse_score", new Document("$sum", "$totaluse_score"))
                .append("totalordergive_score", new Document("$sum", "$totalordergive_score")));
        List<Document> doclist = new ArrayList<>();
        doclist.add(match);
        doclist.add(group);
        List<String> list = this.findAggregate(collectionName + companyid, doclist);
        MemberShipEntity entity;
        if (!list.isEmpty()) {
            entity = new Gson().fromJson(list.get(0), MemberShipEntity.class);
        } else {
            entity = new MemberShipEntity();
        }
        return entity;
    }

    /**
     * 激活会员
     */
    @Override
    public boolean activationMember(int company_id, String phone, String unionId) {
        Bson filter = Filters.and(Filters.eq("phone", phone), Filters.eq("company_id", company_id));
        List<String> list = this.findFilter(collectionName + company_id, filter);
        if (list.size() == 0) {
            return false;
        }
        MemberShipEntity mEntity = new Gson().fromJson(list.get(0), MemberShipEntity.class);
        // 根据手机号查询到会员,修改状态为2:已激活(1:未激活,2:已激活,3:锁定)
        mEntity.setState(2);
        mEntity.setUnionid(unionId);
        String json = new Gson().toJson(mEntity);
        Document doc = Document.parse(json);
        return this.updateOne(collectionName + company_id, filter, doc, false);
    }

    @Override
    public boolean updateRemarks(int company_id, int member_id, String remarks) {
        Bson filter1 = Filters.eq("company_id", company_id);
        Bson filter2 = Filters.eq("member_id", member_id);
        Bson and = Filters.and(filter1, filter2);
        MemberShipEntity memberEntity = new Gson().fromJson(findFilter(collectionName + company_id, and).get(0),
                MemberShipEntity.class);
        memberEntity.setRemarks(remarks);
        return this.updateOne(collectionName + company_id, and,
                Document.parse(new Gson().toJson(memberEntity)), false);
    }

    @Override
    public boolean updateLable(int company_id, int member_id, String fanLanbleList) {
        Bson filter1 = Filters.eq("company_id", company_id);
        Bson filter2 = Filters.eq("member_id", member_id);
        Bson and = Filters.and(filter1, filter2);
        MemberShipEntity memberEntity = new Gson().fromJson(findFilter(collectionName + company_id, and).get(0),
                MemberShipEntity.class);
        memberEntity.setLabel(fanLanbleList);
        return this.updateOne(collectionName + company_id, and, Document.parse(new Gson().toJson(memberEntity)), false);
    }

    @Override
    public boolean deleteLable(int company_id, int member_id, String fanLanble) {
        Bson filter1 = Filters.eq("company_id", company_id);
        Bson filter2 = Filters.eq("member_id", member_id);
        Bson and = Filters.and(filter1, filter2);
        MemberShipEntity memberEntity = new Gson().fromJson(findFilter(collectionName + company_id, and).get(0),
                MemberShipEntity.class);
        String fanLanbleList = memberEntity.getLabel();
        String[] split = fanLanbleList.split(",");
        List<String> list = new ArrayList<>();
        for (String string : split) {
            list.add(string);
        }
        for (int i = 0; i < list.size(); i++) {
            if (fanLanble.equals(list.get(i))) {
                list.remove(list.get(i));
                break;
            }
        }
        String join = StringUtils.join(list.toArray(), ",");
        memberEntity.setLabel(join);
        return this.updateOne(collectionName + company_id, and,
                Document.parse(new Gson().toJson(memberEntity)), false);
    }

    @Override
    public int getMemebrNumByFilter(int company_id, Bson bson) {
        MongoCollection<Document> dbCollection = getCollection(collectionName + company_id);
        return (int) dbCollection.count(bson);
    }

    @Override
    public List<String> getMembersByFilterSortSkipLimt(int company_id, Bson bson, Bson sort, int skip, int pageSize) {
        List<String> list = this.findFilterSortSkipLimit(collectionName + company_id, bson,
                sort, skip, pageSize);
        return list;
    }

    @Override
    public boolean incEntity(int companyid, Bson filter, Document doc) {

        boolean result = this.update(collectionName + companyid, filter,
                new Document("$inc", doc), false);
        return result;
    }

    @Override
    public boolean exportQueryMember(int company_id, String json) {
        return this.inSert(collectionNameExport + company_id, json);
    }

    @Override
    public List<String> findLimit(int company_id, Bson filter, Bson filterSort) {
        return this.findFilterSort(collectionName + company_id, filter, filterSort);
    }

    @Override
    public String findOneAndUpdate(int companyId, Bson bson, Document document, boolean bool) {

        return super.findOneAndUpdate(collectionName + companyId, bson, new Document("$set", document), bool);
    }

    @Override
    public int statististics(int company_id, Bson bson) {
        return this.statististics(collectionName + company_id, bson);
    }

    @Override
    public List<MemberShipEntity> findOrdersByFilterSortSkipLimt(int company_id, Bson bson, Bson sort,
                                                                 int skip, int limit) {
        List<MemberShipEntity> list = new ArrayList<MemberShipEntity>();
        MongoCollection<Document> dbCollection = getCollection(collectionName + company_id);
        FindIterable<Document> dbCursor = dbCollection.find(bson).sort(sort).skip(skip).limit(limit);
        dbCursor.forEach(new Block<Document>() {
            public void apply(final Document document) {
                String a = document.toJson();
                MemberShipEntity memberShipEntity = new Gson().fromJson(a, MemberShipEntity.class);
                list.add(memberShipEntity);
            }
        });
        return list;
    }

}
